<!--  -->
<template>
  <div style="padding-top:100px">
    <div class="app-title-container title-position">
      <modules-title titleName="送检申请">
        <template slot="btn">
          <el-button class="filter-item" type="primary"
                     v-hasPermi="{v:['sampleInspection:applied:add']}"
                     size="small" @click="handleAdd">创建送检申请
          </el-button>
        </template>
      </modules-title>
    </div>

    <div style="padding:20px">
      <!-- 搜索 -->
      <el-form :inline="true">
        <el-form-item style="margin-right:40px">
          <el-select v-model="queryParams.search_type" placeholder="所有状态" @change="handlSearch"
                     size="small">
            <el-option label="所有" :value="0"></el-option>
            <el-option label="我申请的" :value="1"></el-option>
            <el-option label="我参与项目申请的" :value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="请验类型" style="margin-right:40px">
          <el-select v-model="queryParams.inspection_type" placeholder="请验类型"
                     @change="handlInspection" size="small">
            <el-option v-for="(item,index) in demandSourceOptions" :key="index" :label="item.dict_val"
                       :value="item.dict_key"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="项目" style="margin-right:40px">
          <el-select v-model="queryParams.project_id" filterable placeholder="项目名称(可搜索)"
                     @change="handlProject" size="small">
            <el-option v-for="dict in project" :key="dict.project_id"
                       :label="`${dict.project_name}(${ dict.project_phases_id === '1' ? '临床前研究' : '临床研究'})`"
                       :value="dict.id"/>
          </el-select>
        </el-form-item>
        <el-form-item label="状态" style="margin-right:40px">
          <el-select v-model="queryParams.inspection_status" @change="handlSatus" size="small">
            <el-option v-for="dict in inspection" :key="dict.value" :label="dict.label"
                       :value="dict.value"/>
          </el-select>
        </el-form-item>
        <el-form-item label="关键字" style="margin-right:40px">
          <el-input v-model="queryParams.select_str" placeholder="请输入关键字"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button class="filter-item" type="primary" size="small" @click="handleQuery">搜索
          </el-button>
          <el-button plain @click="resetQuery">重置
          </el-button>
        </el-form-item>
      </el-form>

      <!--表格-->
      <el-table :data="appliedList" size="medium" border @row-click="aloneClick"
                :cell-style="cellStyle">
        <el-table-column prop="inspection_no" label="送检单号" align="center"/>
        <el-table-column prop="sample_info.name" label="检品名称" header-align="center"
                         :show-overflow-tooltip="true"/>
        <el-table-column prop="inspection_type_name" label="请验类型" align="center"/>
        <el-table-column prop="creator_name" label="请验人" align="center"/>
        <el-table-column label="请验时间" align="center">
          <template #default="{row}">
            {{ dateFormat1('yyyy-mm-dd',row.created_at)}}
          </template>
        </el-table-column>
        <el-table-column prop="project_name" label="项目名称" :show-overflow-tooltip="true" header-align="center"/>
        <el-table-column label="状态" align="center">
          <template #default="{row}">
            {{status(row.inspection_status)}}
          </template>
        </el-table-column>
        <el-table-column label="操作" header-align="center">
          <template #default="{row}">
            <el-button type="text" size="medium"
                       v-if="row.inspection_status ===5"
                       @click="handlReport(row.id)">查看报告
            </el-button>
            <el-button type="text" size="medium" @click="cancelOperation('ApprovalCheck',row.apply_check.id)"
                       v-if="row.apply_check.Cancelable && row.apply_check.check_creator_id == userInfo">
              撤销审批
            </el-button>
            <el-button type="text" size="medium" @click="cancelOperation('RepealCheck',row.undo_check.id)"
                       v-if="row.undo_check &&  row.undo_check.Cancelable && row.undo_check.check_creator_id == userInfo">
              撤销审批
            </el-button>

            <el-button type="text" size="medium"
                       v-if="row.inspection_status === 2 && row.if_undo === 0 &&row.creator_id === userInfo"
                       @click="handlUndo(row.id)">撤销检验
            </el-button>
            <el-button type="text" size="medium" @click="handlEdit(row.id)"
                       v-if="row.inspection_status == 6 && row.apply_check.check_creator_id == userInfo">
              编辑
            </el-button>

          </template>
        </el-table-column>
      </el-table>

      <!--页码-->
      <pagination style="display:flex;justify-content:flex-end;" :total="total"
                  :page.sync="queryParams.pager.skip" :limit.sync="queryParams.pager.limit"
                  @pagination="pagination"/>

      <!--对话框 -->
      <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body
                 :before-close="cancel" :close-on-click-modal="false" v-if="open">

        <el-form ref="formOpen" :model="formOpen" :rules="rules" label-width="120px" size="small">
          <!-- 请验申请审批 1-->
          <div v-if="openBoole === 1">
            <el-form-item label="审批意见" prop="check_advice">
              <el-input v-model="formOpen.check_advice" placeholder="请输入审批意见"/>
            </el-form-item>
          </div>
        </el-form>

        <div slot="footer" class="dialog-footer">
          <el-button plain size="small" @click="cancel">取 消
          </el-button>
          <el-button v-if="openBoole === 1" type="warning" size="small" @click="refused">拒绝
          </el-button>
          <el-button size="small" type="primary" @click="submitForm">
            <span v-if="openBoole === 1">通过</span>
            <span v-else-if="openBoole === 2">确定</span>
            <span v-else-if="openBoole === 3">保存</span>
            <span v-else-if="openBoole === 4">提交审批</span>
          </el-button>
        </div>
      </el-dialog>

      <!--查看报告 -->
      <reportdialog  ref="reportdialog"  :formOpen="formOpen" :rowList="rowList"/>

    </div>

  </div>

</template>

<script>
  import {
    applyList,
    projectName,
    applyCheck,
    reportCheck,
    undoCheck,
    allocation,
    samples,
    report,
    undo,
    applyViewReport,
    lookInfoSet,
    projectNamesss, sampleListTable,
    sampleListReport
  } from '@/api/sampleInspection'
  // import { dateFormat1 } from "@/utils/ruoyi";
  export default {
    components: {
      reportdialog: () => import('../../modules/reportList.vue')
    },
    data() {
      return {
        activeNames: '',
        queryParams: {
          select_str: '',
          inspection_type: '',
          project_id: '',
          inspection_status: -1,
          search_type: 0,
          pager: {
            limit: 10,
            skip: 1
          }
        },
        sample: [],
        appliedList: [],
        inspection: [
          //状态
          { label: ' 全部 ', value: -1 },
          { label: '检验审批中 ', value: 0 },
          { label: '请验申请拒绝 ', value: 1 },
          { label: ' 检验中', value: 2 },
          { label: '撤销审批中', value: 3 },
          { label: '已撤销 ', value: 4 },
          { label: '已结束 ', value: 5 },
          { label: '已回退 ', value: 6 }
        ],
        inspector: [
          { label: '检验员一', value: '1' },
          { label: '检验员二', value: '0' }
        ], //检验员
        participants: [
          { label: '参与人一', value: '1' },
          { label: '参与人二', value: '2' },
          { label: '参与人三', value: '3' },
          { label: '参与人四', value: '4' }
        ],
        location: [
          { label: '位置一', value: '1' },
          { label: '位置二', value: '0' }
        ],
        project: [],
        total: 0,
        title: '',
        open: false,
        openBoole: 0,
        formOpen: {
          id: '0', //主键id
          check_status: undefined, //审批 1 通过  2 拒绝
          check_advice: '', //审批建议
          inspection_user_id: '', //分配的检验员的id
          inspection_user_name: '', //分配的检验员的名称
          reserve_sample_num: undefined, //留样的数量
          reserve_sample_date: '', //留样的有效期
          report: '', //报告内容
          participants_user_id: [], //参与人id
          participants_user_name: [], //参与人名字
          location_id: '', //位置id
          location_name: '', //位置name
          reserve_sample_no: '', //留样编号
          packaging: '', //留样包装
          inspection_conclusion: 1,
          remark: '',
          sample_num: null,
          return_sample_check_num: null,
          name: '',
          if_reserve_sample: 1,
          storage_conditions: '',
          quality_standard_type: 1,
          quality_standard_id: '',
          quality_standard_name: '',
          quality_standard_file: [],
          inspection_date: '',
          tableResults: {
            id: '',
            report: [],//
            computation_sheet: [], //计算表格
            inspection_map: []//  检验图谱
          },
          relation_plan_id: ''
        },
        rules: {
          check_advice: [
            { required: true, message: '请输入审批意见', trigger: 'blur' }
          ],
          inspection_user_id: [
            { required: true, message: '请选择检验员', trigger: 'change' }
          ],
          reserve_sample_num: [
            {
              required: true,
              message: '请输入留样数量',
              trigger: 'blur',
              type: 'number'
            },
            { pattern: /^[1-9]([0-9])*$/, message: '只能输入正整数' }
          ],
          reserve_sample_date: [
            { required: true, message: '时间不能为空', trigger: 'change' }
          ],
          participants_user_id: [
            { required: true, message: '请选择参与人', trigger: 'change' }
          ],
          location_id: [
            { required: true, message: '请选择位置', trigger: 'change' }
          ],
          reserve_sample_no: [
            { required: true, message: '请输入留样编号', trigger: 'blur' }
          ],
          packaging: [
            { required: true, message: '请输入留样包装', trigger: 'blur' }
          ]
        },
        inspection_status: undefined,
        inspection_joiner: [], //参与人
        rowList: {},
        openReport: false,
        fileList: [],
        fileType: undefined,
        userInfo: '',
        demandSourceOptions: []
      }
    },
    //是计算属性，也可以理解为一个方法。
    computed: {
      status() {
        return function(val) {
          let a = ''
          this.inspection.forEach(element => {
            if (val === element.value) {
              a = element.label
            }
          })
          return a
        }
      }
    },

    //属性是手动定义的所需监听的值
    watch: {},

    //生命周期 - 创建完成（访问当前this实例）
    created() {
      this.userInfo = this.$store.getters.userInfo.user.id
      this.remoteMethod()
      this.applyListData()
      this.getSysAllDic()
    },

    beforeRouteEnter(to, from, next) {
      to.params.refresh = from.params.refresh
      next()
    },
    activated() {
      if (this.$route.params.refresh) {
        this.applyListData()
      }
    },

    //生命周期 - 挂载完成（访问DOM元素）
    mounted() {
    },

    //是Vue实例对象上绑定的方法，供当前Vue组件作用域内使用，
    methods: {
      getSysAllDic() {
        lookInfoSet({ dictType: 'inspection_type' }).then(res => {
          if (res.code == 200) {
            this.demandSourceOptions = res.data
            let index = this.demandSourceOptions.findIndex(a => a.dict_key === 'inspection_type_wd')
            if (index !== -1) {
              this.demandSourceOptions.splice(index, 1)
            }
          }
        })
      },

      //获取项目名称
      async remoteMethod(queryString) {
        let res = await projectNamesss()
        if (res.code === 200) {
          this.project = res.data.data || []
        }
      },

      //获取列表
      applyListData() {
        console.log(this.queryParams, '---------')
        applyList(this.queryParams).then(res => {
          if (res.code === 200) {
            this.appliedList = res.data.data || []
            this.total = res.data.total
          }
        })
      },

      //页码条数
      pagination(val) {
        this.queryParams.pager.skip = val.page
        this.queryParams.pager.limit = val.limit
        this.applyListData()
      },

      //创建送检申请
      handleAdd() {
        this.$router.push('/sampleInspection/applied/createTest')
      },

      handlSearch(val) {
        this.queryParams.search_type = val
        this.queryParams.pager.skip = 1
        this.applyListData()
      },

      handlInspection(val) {
        this.queryParams.inspection_type = val
        this.queryParams.pager.skip = 1
        this.applyListData()
      },

      handlProject(val) {
        console.log(val)
        this.queryParams.project_id = val
        this.queryParams.pager.skip = 1
        this.applyListData()
      },

      handlSatus(val) {
        this.queryParams.inspection_status = val
        this.queryParams.pager.skip = 1
        this.applyListData()
      },

      //搜索
      handleQuery() {
        this.queryParams.pager.skip = 1
        this.applyListData()
      },

      //重置
      resetQuery() {
        this.queryParams = {
          inspection_type: '',
          project_id: '',
          inspection_status: -1,
          search_type: 0,
          pager: {
            limit: 10,
            skip: 1
          }
        }
        this.applyListData()
      },

      //查看详情
      handlDetails(id) {
        this.$router.push({
          path: '/sampleInspection/details',
          query: { type: 1, id: id }
        })
      },

      //查看详情
      aloneClick(row, column, event) {
        if (column.label === '操作') {
          return
        }
        this.$router.push({
          path: '/sampleInspection/details',
          query: { type: 1, id: row.id }
        })
      },

      cellStyle(data) {
        return 'cursor:pointer;'
      },

      //检验员事件
      onChangeInsp(val) {
        this.formOpen.inspection_user_id = val
        this.inspector.forEach(item => {
          if (item.value === val) {
            this.formOpen.inspection_user_name = item.label
          }
        })
      },

      //参与人事件
      onChangeSelect(val) {
        let arr = []
        this.formOpen.participants_user_id = val
        this.participants.forEach(item => {
          val.forEach(id => {
            if (item.value === id) {
              arr.push({
                id: id,
                name: item.label
              })
            }
          })
        })
        this.inspection_joiner = [...new Set(arr)]
      },

      //留样位置
      onChangeLoca(val) {
        this.formOpen.location_id = val
        this.location.forEach(item => {
          if (item.value === val) {
            this.formOpen.location_name = item.label
          }
        })
      },

      //撤销审批
      cancelOperation(val, id) {
        const subdata = {
          flow_id: id,
          model_type: val
        }
        this.$comFun.cancelFunc(subdata)
          .then(() => {
            this.$message({
              type: 'success',
              message: '已撤销'
            })
            this.applyListData()
          })
          .catch(err => {
            this.$message.error(err)
          })
      },

      //撤销检验
      handlUndo(id) {
        console.log(id)
        this.$confirm('确认要撤销检验', '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(_ => {
            undo(id).then(res => {
              if (res.code === 200) {
                this.$message.success('操作成功')
                this.applyListData()
              } else {
                this.$message.error(res.msg)
              }
            })
          })
          .catch(_ => {
          })
      },

      //编辑
      handlEdit(id) {
        this.$router.push({
          path: '/sampleInspection/applied/createTest',
          query: { s_id: id }
        })
      },

      //审批
      handlAnd(row) {
        let _self = this
        if (row.inspection_status === 0) {
          _self.title = '检验审批中'
          _self.inspection_status = 0
        } else if (row.inspection_status === 3) {
          _self.title = '撤销审批中'
          _self.inspection_status = 3
        }
        _self.openBoole = 1
        _self.open = true
        _self.formOpen.id = row.id
      },

      //分配
      handlDistri(row) {
        let _self = this
        _self.title = '请选择检验员'
        _self.openBoole = 2
        _self.open = true
        _self.formOpen.id = row.id
      },

      //留样
      handlReten(row) {
        let _self = this
        _self.title = '留样'
        _self.openBoole = 3
        _self.open = true
        _self.formOpen.id = row.id
        _self.rowList = row
      },

      //提交检验结果
      handlResults(row) {
        let _self = this
        _self.title = '上传检验报告'
        _self.openBoole = 4
        _self.open = true
        _self.formOpen.id = row.id
      },

      activeClick(val){
        this.activeNames = val
      },

      //查看报告
      handlReport(id) {
        let row = {}
        sampleListReport(id).then(res=>{
          if(res.code === 200){
            row = res.data
            this.rowList = row
            this.formOpen.tableResults = {
              computation_sheet: [],
              report: [],
              inspection_map: []
            }
            if (row.computation_sheet && row.inspection_result && row.inspection_map) {
              this.formOpen.tableResults.computation_sheet = JSON.parse(JSON.stringify(row.computation_sheet)) || []
              this.formOpen.tableResults.report = JSON.parse(JSON.stringify(row.inspection_result)) || []
              this.formOpen.tableResults.inspection_map = row.inspection_map || []
              for (let i = 0; i < this.formOpen.tableResults.report.length; i++) {
                this.formOpen.tableResults.report[i].boole = true
                if (row.experiment_table_info_map) {
                  this.formOpen.tableResults.report[i].ruleForm = row.experiment_table_info_map[this.formOpen.tableResults.report[i].batch_no]

                } else {
                  if (row.inspection_type === 'inspection_type_wd') {
                    sampleListTable({ id: row.relation_plan_id }).then(res => {
                      if (res.code === 200) {
                        this.formOpen.tableResults.report.forEach(item => {
                          if (res.data[item.batch_no]) {
                            item.ruleForm = res.data[item.batch_no]

                          }
                        })
                      }
                    })
                  }
                }
              }
            }
            this.$refs.reportdialog.openport()
            this.activeNames = this.formOpen.tableResults.report[0].batch_no
          }
        })

      },

      //取消
      cancel() {
        this.open = false
        this.formOpen = {
          id: '0', //主键id
          check_status: undefined, //审批 1 通过  2 拒绝
          check_advice: '', //审批建议
          inspection_user_id: '', //分配的检验员的id
          inspection_user_name: '', //分配的检验员的名称
          reserve_sample_num: undefined, //留样的数量
          reserve_sample_date: '', //留样的有效期
          report: '', //报告内容
          participants_user_id: [], //参与人id
          participants_user_name: [], //参与人名字
          location_id: '', //位置
          location_name: '', //位置name
          reserve_sample_no: '', //留样编号
          packaging: '' //留样包装
        }
        this.inspection_joiner = []
        this.sample_info = [] //样品信息
        this.apply_inspection_user = [] //检验负责人
        this.inspection_user = {} //请检人
      },

      //拒绝
      refused() {
        this.$refs.formOpen.validate(valid => {
          if (valid) {
            let commit = undefined,
              data = {},
              msg = ''
            if (this.inspection_status === 0) {
              commit = applyCheck
            } else if (this.inspection_status === 3) {
              commit = undoCheck
            }
            data = {
              id: this.formOpen.id,
              check_status: 2,
              check_advice: this.formOpen.check_advice
            }
            msg = this.title + '已拒绝'
            commit(data).then(res => {
              if (res.code === 200) {
                this.$message.success(msg)
                this.open = false
                this.cancel()
                this.applyListData()
              } else {
                this.$message.error(res.msg)
              }
            })
          } else {
            return false
          }
        })
      },

      //提交
      submitForm() {
        let _self = this
        _self.$refs.formOpen.validate(valid => {
          if (valid) {
            let commit = undefined,
              data = {},
              msg = ''
            if (_self.openBoole === 1) {
              if (_self.inspection_status === 0) {
                commit = applyCheck
              } else if (_self.inspection_status === 3) {
                commit = undoCheck
              }
              data = {
                id: _self.formOpen.id,
                check_status: 1,
                check_advice: _self.formOpen.check_advice
              }
              msg = _self.title + '已同意'
            } else if (_self.openBoole === 2) {
              commit = allocation
              data = {
                id: _self.formOpen.id,
                inspection_header: {
                  id: _self.formOpen.inspection_user_id,
                  name: _self.formOpen.inspection_user_name
                },
                inspection_joiner: _self.inspection_joiner
              }
              msg = '操作成功'
            } else if (_self.openBoole === 3) {
              commit = samples
              data = {
                inspection_id: _self.formOpen.id,
                expiry_date: _self.formOpen.reserve_sample_date,
                num: Number(_self.formOpen.reserve_sample_num),
                reserve_sample_no: _self.formOpen.reserve_sample_no,
                sample_info: _self.rowList.sample_info,
                apply_inspection_user: _self.rowList.inspection_header,
                inspection_user: {
                  id: _self.rowList.creator_id,
                  name: _self.rowList.creator_name
                },
                location_id: _self.formOpen.location_id,
                location_name: _self.formOpen.location_name,
                packaging: _self.formOpen.packaging,
                project_id: _self.rowList.project_id,
                project_name: _self.rowList.project_name
              }
              msg = _self.title + '已成功'
            } else if (_self.openBoole === 4) {
              commit = report
              data = {
                id: _self.formOpen.id,
                report: _self.$refs.upload.emitFileList()
              }
              msg = _self.title + '已成功'
            }
            commit(data).then(res => {
              if (res.code === 200) {
                _self.$message.success(msg)
                _self.open = false
                _self.cancel()
                _self.applyListData()
              } else {
                _self.$message.error(res.msg)
              }
            })
          } else {
            return false
          }
        })
      }
    }
  }
</script>
<style scoped>
  /* @import url(); 引入css类 */
  ::v-deep .el-button--text {
    padding: 0;
    margin: 0 !important;
    margin-right: 10px !important;
  }
</style>
